<script>
import {  
	    tencentImAuths, //腾讯云IM登录鉴权
		getUserCompanys, //获取全部公司
		getUserInfos, //获取用户信息
	} from 'common/api.js';
import { initWxConfig, setIndexPagetoShare } from 'common/index.js';
import store from 'store/index.js';
import { mapGetters,mapActions,mapState } from 'vuex';
export default {
	created() {
		if (!!this.userSig) {
			
		} else { 
			this.getusersig(); 
		}
		if (!!this.companyInfo) {
			
		} else { 
			this.getinfo(); 
		}
	},
	mounted() {
		/**官网有很多关于关于sdk 其他的监听方法（比如：有新的消息，用户资料更新等等）
		 * 详情可对照： https://imsdk-1252463788.file.myqcloud.com/IM_DOC/Web/SDK.html
		 * 监听的含义：服务端发生了数据变更---前端全局可以接收到变更通知--前端就可以自动触发某个事件来更新相应数据
		 * */
		// 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
		this.tim.on(this.$TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this);
		// 收到新消息
		this.tim.on(this.$TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage);
		// 会话列表更新
		this.tim.on(this.$TIM.EVENT.CONVERSATION_LIST_UPDATED, event => {
			this.$store.commit("updateConversationList", event.data);
		});
	},
	computed: {
		...mapGetters(['userSig','companyInfo','selIndex','userInfo']),
		...mapState({
			isSDKReady: state => state.isSDKReady,
			conversationList: state => state.conversationList,
		}),
	},
	watch: {
		conversationList(val) {
			this.getUserInfo(val)
		},
	},
	methods: {
		...mapActions('user', ['setCompanyInfo','setUserInfo', 'setUserSig','setSelIndex']),
		//获取当前的公司和用户信息
		getinfo() { 
			getUserCompanys().then(res=>{
				if(res.code === 2000){
					let currentSubIndex = 0
					if(!!this.selIndex){
						currentSubIndex = this.selIndex;
					}else{
						this.setSelIndex(currentSubIndex); //选中的公司
					}
					this.setCompanyInfo(res.data[currentSubIndex]) //设置选中公司的缓存
					getUserInfos({
						company_id: res.data[currentSubIndex].id
					}).then(res2 => {
						if (res2.code === 2000) {
							this.setUserInfo(res2.data); //设置用户信息缓存
						}
					})
				}
			})
		},
		//用户IM登录
		getusersig() {
			let _self = this;
			console.log('IM登录')
			//获取im userSig
			tencentImAuths({company_id:this.companyInfo.id}).then(res3 => {
				if (res3.code === 2000) {
					this.setUserSig(res3.data.user_sig)
					console.log('timlogin', _self.companyInfo.id,_self.userInfo.uid)
					//tim登录
					let promise = _self.tim.login({
						userID: _self.companyInfo.id + ':' + _self.userInfo.uid,
						userSig: res3.data.user_sig
					});
					let userInfo = {
						userID: _self.companyInfo.id + ':' + _self.userInfo.uid,
						userSig: res3.data.user_sig
					};
					promise.then((res4) => {
						//登录成功后 更新登录状态
						//this.$store.commit("toggleIsLogin", true);
						//自己平台的用户基础信息
						uni.setStorageSync('userInfo', JSON.stringify(userInfo))
						//tim 返回的用户信息
						uni.setStorageSync('userTIMInfo', JSON.stringify(res4.data))
					}).catch((err) => {
						console.warn('login error:', err); // 登录失败的相关信息
					});
				}
			})
		},
		onReadyStateUpdate({
			name
		}) {
			console.log('message初始化成功')
			const isSDKReady = name === this.$TIM.EVENT.SDK_READY ? true : false;
			//自动监听并更新 sdk 的ready 状态 （未登录是 notReady  登录后是ready）
			this.$store.commit("toggleIsSDKReady", isSDKReady);
			//sdk ready 后  肯定完成了登录操作    这里可以获取用户存储在im的基础信息/离线消息/黑名单列表
		},
	
		onReceiveMessage({
			data: messageList
		}) {
			// this.handleAt(messageList);
			this.$store.commit("pushCurrentMessageList", messageList);
		},
	
		//根据消息列表请求聊天对象的用户信息 并完成数据拼接
		getUserInfo(conversationList) {
			console.log(998,conversationList)
			let unreadCount = 0;
			let count = 0;
			conversationList.forEach((item,index) => {
					if (conversationList.length === (index + 1)) {
						unreadCount += item.unreadCount;
						count = 2;
					} else {
						unreadCount += item.unreadCount;
					}
			})
			if (count === 2 && unreadCount > 0) {
				uni.setTabBarBadge({
					index: 1,
					text: unreadCount + ''
				})
			}else if(count === 2 && unreadCount === 0){
				uni.removeTabBarBadge({
					index: 1,
				})
			}
		},
	},
	onLaunch: function() {
		
	},
	onShow: function() {
		console.log('App Show');
		
	},
	onHide() {
		
	}
};
</script>

<style lang="scss">
// #ifndef APP-PLUS-NVUE (条件编译, 这里的注释符号是必须的)
@import 'styles/iconfont.scss';
@import 'styles/iconfonts.scss';
/* 导入全局样式 自定义*/
@import '/static/css/common.css';
//引入动画样式
//@import "/static/css/animate.css";
/*每个页面公共css */
page {
	background-color: $uni-bg-color;
	height: 100%;
}
@font-face {
	font-family: PingFang SC;
}
image {
	display: block;
}
view,
scroll-view,
swiper,
swiper-item,
cover-view,
cover-image,
icon,
text,
rich-text,
progress,
button,
checkbox,
form,
input,
label,
radio,
slider,
switch,
textarea,
navigator,
audio,
camera,
image,
video {
	box-sizing: border-box;
}
.bold {
	font-weight: bold;
}
.flex-wrap {
	display: flex;
	flex-direction: flex-wrap;
	align-items: center;
}
.flex-column {
	display: flex;
	flex-direction: column;
	align-items: center;
}
button {
	&:after {
		border: 0;
	}
}
.assemble-btn {
	color: #fff;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}
.empty-btn {
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}
// #endif
</style>
